package com.why.websocketmqttstudy.why.websocket.handler;

import com.alibaba.fastjson.JSONObject;
import com.why.websocketmqttstudy.why.entity.User;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class WebSocketHandler extends SimpleChannelInboundHandler<Object> {

//	private final static Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);

	private static WebSocketMsgFactory webSocketMsgFactory;

	private WebSocketServerHandshaker handshaker;

	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
//        logger.info("客户端加入连接："+ctx.channel());
        //ChannelSupervise.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
//        logger.info("客户端断开连接："+ctx.channel());
        ChannelHandlerPool.removeChannel(ctx.channel());
        
        //ChannelSupervise.removeChannel(ctx.channel());
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) 
        {
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }
        else if (msg instanceof WebSocketFrame) 
        {
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 唯一的一次http请求。
     * 该方法用于处理websocket握手请求
     */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) 
    {
        //如果HTTP解码失败，返回异常。要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) 
        {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        
        String jwt = req.headers().get("Sec-WebSocket-Protocol");

        if(StringUtils.isBlank(jwt))
        {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
        }
        
//        User user = UserHandler.getUserInfo(jwt, User.class);
        User user = new User();

        if (user == null) {
//        	logger.error("凭证过期:{}", jwt);
        	sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
        }

        // 增加客户端连接
        Channel channel = ChannelHandlerPool.addChannel(ctx.channel(), user);
        if(channel!=null){
            JSONObject data = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msgType","CloseWebSocket");
            data.put("userCode",user.getUserName());
            jsonObject.put("data",data);
            channel.writeAndFlush(new TextWebSocketFrame(jsonObject.toJSONString()));
        }
//        logger.info(user.getUserName()+"连接WebSocket");

        //String uri = req.uri();
        //if (StringUtils.isEmpty(uri))
        //{
         //   sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
          //          HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
      //  }

    	//Map<String, String> map = getParams(uri);
    	//if(!map.containsKey("token"))
       //     sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));

    	//String token = map.get("token");
    	//if(!"1234567".equals(token))
    	//{
        //    sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
       //             HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
    	//}

        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), jwt, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) 
        {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    @Autowired
    public void setWebSocketMsgFactory(WebSocketMsgFactory webSocketMsgFactory){
        WebSocketHandler.webSocketMsgFactory = webSocketMsgFactory;
    }

    /*
    对WebSocket请求进行处理
     */
    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否ping消息，如果是，则构造pong消息返回。用于心跳检测
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
//        	logger.info("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(
                    String.format("%s frame types not supported", frame.getClass().getName()));
        }
        //处理客户端请求并返回应答消息
        String request = ((TextWebSocketFrame) frame).text();
//        logger.info("服务端收到：" + request);

//        WebSocketReq webSocketReq = JSONObject.parseObject(request, WebSocketReq.class);

//        logger.info("服务端收到：" + webSocketReq);

//        WebSocketMsgHandler handler = webSocketMsgFactory.getHandler(webSocketReq.getSign());
//
//        if(handler!=null){
//            handler.handle(webSocketReq.getData(),ctx.channel());
//        }

        // 谁发的返回给谁
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //JSONObject jsonObject = new JSONObject();
        //jsonObject.put("time",format.format(new Date()));
        //jsonObject.put("channelId",ctx.channel().id().asShortText());
        //jsonObject.put("request",request);
        //TextWebSocketFrame tws = new TextWebSocketFrame(jsonObject.toJSONString());
        
        //ChannelHandlerPool.findChannel(ctx.channel().id().asShortText()).writeAndFlush(tws);
    }

    private static Map<String, String> getParams(String uri) {
        Map<String, String> params = new HashMap<>(10);

        int idx = uri.indexOf("?");
        if (idx != -1) {
          String[] paramsArr = uri.substring(idx + 1).split("&");

          for (String param : paramsArr) {
            idx = param.indexOf("=");
            params.put(param.substring(0, idx), param.substring(idx + 1));
          }
        }

        return params;
      }
    
    private static String getWebSocketLocation(FullHttpRequest req) {
        String location =  req.headers().get(HttpHeaderNames.HOST);
            return "ws://" + location;
    }
    
    /**
     * 拒绝不合法的请求，并返回错误信息
     */
    private static void sendHttpResponse(ChannelHandlerContext ctx,FullHttpRequest req, DefaultFullHttpResponse res) 
    {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }

        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

}
